package com.swt.gap.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.swt.gap.common.PageResult;
import com.swt.gap.common.PermissionService;
import com.swt.gap.common.constant.FileFromTypeConstant;
import com.swt.gap.dao.FileClassDao;
import com.swt.gap.dao.FileDao;
import com.swt.gap.model.entity.File;
import com.swt.gap.model.graphmodel.ResourceCenterFileInfo;
import com.swt.gap.model.vo.MoveFile;
import com.swt.gap.model.vo.MoveRepeatFileVO;
import com.swt.gap.model.vo.UploadFileVO;
import com.swt.gap.model.vo.fileclass.UserFileClassVO;
import com.swt.gap.model.vo.resourcecenter.*;
import com.swt.gap.service.ResourceService;
import com.swt.gap.service.SysGroupService;
import com.swt.gap.util.UserLoginUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zqw
 * @date 2020/5/12 14:56
 */

@Service
public class ResourceServiceImpl implements ResourceService {

    private final FileDao fileDao;
    private final FileClassDao fileClassDao;
    private final SysGroupService sysGroupService;
    private final PermissionService permissionService;

    public ResourceServiceImpl(FileDao fileDao, FileClassDao fileClassDao,
                               SysGroupService sysGroupService, PermissionService permissionService) {
        this.fileDao = fileDao;
        this.fileClassDao = fileClassDao;
        this.sysGroupService = sysGroupService;
        this.permissionService = permissionService;
    }

    @Override
    public List<ResourceCenterFileFormVO> getIndexData(int userId) {
        List<ResourceCenterFileInfo> resourceCenterFileInfoList = fileDao.getAllFile(userId);
        //第一层，数据来源
        List<ResourceCenterFileFormVO> resourceCenterFileFormVOList = new ArrayList<>();

        ResourceCenterFileFormVO resourceCenterFileFormVO = new ResourceCenterFileFormVO();
        resourceCenterFileFormVO.setFileFormId(2);
        resourceCenterFileFormVO.setFileFormName("私有资源");

//        ResourceCenterFileFormVO out = new ResourceCenterFileFormVO();
//        out.setFileFormId(1);
//        out.setFileFormName("公共资源");

        int i = 0;
        if(resourceCenterFileInfoList.isEmpty()){
            resourceCenterFileFormVOList.add(resourceCenterFileFormVO);
//            resourceCenterFileFormVOList.add(out);
            return resourceCenterFileFormVOList;
        }
        if (resourceCenterFileInfoList.get(i).getCountTotle() != null) {
            resourceCenterFileFormVO.setTotleFileNumber(resourceCenterFileInfoList.get(i).getCountTotle());
        } else {
            while (resourceCenterFileInfoList.get(i).getCountTotle() == null) {
                i++;
                if (i >= resourceCenterFileInfoList.size()) {
                    resourceCenterFileFormVO.setTotleFileNumber(0);
                    break;
                }
                if (resourceCenterFileInfoList.get(i).getCountTotle() != null) {
                    resourceCenterFileFormVO.setTotleFileNumber(resourceCenterFileInfoList.get(i).getCountTotle());
                    break;
                }
            }
        }
        //第二层，数据分类
        List<ResourceCenterFileClassDataVO> parentList = new ArrayList<>();
        List<Integer> integerList = new ArrayList<>();
        //获取分类
        for (ResourceCenterFileInfo resourceCenterFileInfo : resourceCenterFileInfoList) {
            //判断是否有
            if (!integerList.contains(resourceCenterFileInfo.getFileClassId())) {
                integerList.add(resourceCenterFileInfo.getFileClassId());

                ResourceCenterFileClassDataVO parent = new ResourceCenterFileClassDataVO();
                parent.setFileName(resourceCenterFileInfo.getClassName());
                parent.setFileClassId(resourceCenterFileInfo.getFileClassId());
                if (resourceCenterFileInfo.getCountPart() == null) {
                    parent.setFileNumber(0);
                } else {
                    parent.setFileNumber(resourceCenterFileInfo.getCountPart());
                }
                if (resourceCenterFileInfo.getFileId() == null) {
                    parentList.add(parent);
                    continue;
                } else {
                    List<ResourceCenterFileInfoVO> childrenList = new ArrayList<>();
                    ResourceCenterFileInfoVO children = new ResourceCenterFileInfoVO();
                    children.setFileId(resourceCenterFileInfo.getFileId());
                    children.setFileName(resourceCenterFileInfo.getFileName());
                    children.setFileType(resourceCenterFileInfo.getFileType());
                    children.setCreateTime(resourceCenterFileInfo.getCreatedTime());
                    childrenList.add(children);

                    parent.setResourceCenterFileInfoVOS(childrenList);
                }
                parentList.add(parent);
            } else {
                for (ResourceCenterFileClassDataVO parent : parentList) {
                    if (parent.getFileClassId() == resourceCenterFileInfo.getFileClassId()) {

                        ResourceCenterFileInfoVO children = new ResourceCenterFileInfoVO();
                        children.setFileId(resourceCenterFileInfo.getFileId());
                        children.setFileName(resourceCenterFileInfo.getFileName());
                        children.setFileType(resourceCenterFileInfo.getFileType());
                        children.setCreateTime(resourceCenterFileInfo.getCreatedTime());
                        parent.getResourceCenterFileInfoVOS().add(children);
                    }
                }
            }


        }

        List<ResourceCenterFileClassDataVO> collect = parentList.stream()
                .sorted(Comparator.comparing(ResourceCenterFileClassDataVO::getFileName))
                .collect(Collectors.toList());

        resourceCenterFileFormVO.setResourceCenterFileClassDataVOS(collect);

        //////////////外部的假数据
//        out.setTotleFileNumber(resourceCenterFileFormVO.getTotleFileNumber());
//        out.setResourceCenterFileClassDataVOS(collect);
//        resourceCenterFileFormVOList.add(out);
        ///////////外部的假数据


        resourceCenterFileFormVOList.add(resourceCenterFileFormVO);


        return resourceCenterFileFormVOList;
    }

    @Override
    public List<ResourceNumber> countNumber(int userId) {
        List<ResourceNumber> resourceNumber = new ArrayList<>();
        List<ResourceNumber> resourceNumberList = fileDao.countResourceNumber(userId);
        ResourceNumber inNum = new ResourceNumber(FileFromTypeConstant.FILE_TYPE_FORM_OUT, 0);
        ResourceNumber outNum = new ResourceNumber(FileFromTypeConstant.FILE_TYPE_FORM_IN, 0);
        resourceNumber.add(inNum);
        resourceNumber.add(outNum);
        for (ResourceNumber resource : resourceNumberList) {
            for (ResourceNumber resourceNum : resourceNumber) {
                if (resource.getFileFormType() == resourceNum.getFileFormType()) {
                    resourceNum.setFileNumber(resource.getFileNumber());
                }
            }
        }
        return resourceNumber;
    }

    @Override
    public PageResult<UserFileClassVO> dataStatistics(Integer pageNum, Integer pageSize) {
        Integer userId = UserLoginUtils.getUserId();
        List<Integer> userIds = sysGroupService.listSameGroupUserByUserId(userId);

        if (null != pageNum && 0 != pageNum && null != pageSize &&  0 != pageSize) {
            PageHelper.startPage(pageNum, pageSize);
        }
        Page<UserFileClassVO> userFileClassList = fileClassDao.getUserFileClassList(userIds,null,null);
//                fileClassService.getUserFileClassList(userIds, null, null);

        userFileClassList.getResult().forEach(userFileClassVO -> {
            int fileClassId = userFileClassVO.getFileClassId();
            userFileClassVO.setFormFileCount(fileDao.countByFileClassAndFileType(null, fileClassId, 1));
            userFileClassVO.setDocFileCount(fileDao.countByFileClassAndFileType(null, fileClassId, 2));
            userFileClassVO.setMediaFileCount(fileDao.countByFileClassAndFileType(null, fileClassId, 3));
            userFileClassVO.setEmailFileCount(fileDao.countByFileClassAndFileType(null, fileClassId, 4));

        });
        return new PageResult<>(userFileClassList);
    }

    @Override
    public PageResult<ResourceSearchResultVO> searchResource(Integer location,
                                                             Integer userId,
                                                             Integer fileClassId,
                                                             String keyword,
                                                             Integer orderType,
                                                             Integer pageNum,
                                                             Integer pageSize) {
        //注意要分页
        if (0 != pageNum && 0 != pageSize) {
            PageHelper.startPage(pageNum, pageSize);
        }
        Page<ResourceSearchResultVO> resourceSearchResultPage;
        if (location == 1) {
            resourceSearchResultPage = fileDao.searchResource(userId, keyword);
        } else {
            resourceSearchResultPage = fileDao.searchResourceByKeyWord(userId, fileClassId, orderType, keyword);
        }
        assert resourceSearchResultPage != null;
        if (!resourceSearchResultPage.isEmpty() && StringUtils.isNotBlank(keyword)) {
            for (ResourceSearchResultVO resourceSearchResult : resourceSearchResultPage) {
                String replace = resourceSearchResult.getFileName().replace(keyword, "<em>" + keyword + "</em>");
                resourceSearchResult.setFileName(replace);
                resourceSearchResult.setHasReadPermission(permissionService.hasReadPerm(userId,
                        resourceSearchResult.getCreatedBy(), resourceSearchResult.getPassword()));
                resourceSearchResult.setHasWritePermission(permissionService.hasWritePerm(userId, resourceSearchResult.getCreatedBy()));
                resourceSearchResult.setHasPassword(!org.springframework.util.StringUtils.isEmpty(resourceSearchResult.getPassword()));
                resourceSearchResult.setPassword(null);
                //                resourceSearchResultVO.se
            }
        }

        return new PageResult<>(resourceSearchResultPage);
    }

    @Override
    public List<MoveRepeatFileVO> moveFile(MoveFile moveFile) {
        //获取目标分类的数据；
//        List<File> fileList = fileDao.getFileByClassId(moveFile.getFileClassId());

        //List<Integer> back = judgeFile(moveFile.getFiles(), fileList);
        List<MoveRepeatFileVO> back = repeatFile(moveFile.getFiles(), moveFile.getFileClassId());
        //如果没有重名，移动更新
        if (back.isEmpty()) {
            updateFileClass(moveFile.getFiles(), moveFile.getFileClassId());
        }
        return back;
    }

    @Override
    public int forcedMoveFile(Integer operator, MoveFile moveFile) {
        //获取用户id
//        int userId = UserLoginUtils.getUserId();
//        获取目标分类下的数据
//        List<File> fileList = fileMapper.getFileByClassId(moveFile.getFileClassId());
//        移动中重名文件
//        List<Integer> nList = judgeFile(moveFile.getFiles(), fileList);


        //移动中重名文件
        List<Integer> nList = new ArrayList<>();
        //目标类中重名的文件id
        List<Integer> origin = new ArrayList<>();
        //获取重名的文件id
        List<MoveRepeatFileVO> back = repeatFile(moveFile.getFiles(), moveFile.getFileClassId());

        for (MoveRepeatFileVO moveRepeatFileVO : back) {
            nList.add(moveRepeatFileVO.getOriginFile());
            origin.add(moveRepeatFileVO.getTarget());
        }

        //重名文件
        // List<Integer> nList = moveFileParamVO.getRepeatFiles();
        //可直接更新的

        List<Integer> yList = moveFile.getFiles();
        yList.removeAll(nList);

        updateFileClass(yList, moveFile.getFileClassId());

        //直接覆盖

        if (operator == 1) {
            //删除原有的重名数据
            File originFile = new File();
            for (Integer originId : origin) {
                originFile.setFileId(originId);
                originFile.setIsDeleted(true);
                fileDao.updateByPrimaryKeySelective(originFile);
            }
            //更新新的
            File newFile = new File();
            for (Integer id : nList) {
                //删除原有的重名数据
//                file.setFileId(fileMapper.selectSameFile(fileMapper.selectByPrimaryKey(id).getFileName(),
//                        null,moveFile.getFileClassId(),userId).getFileId());
//                file.setIsDeleted(true);
//                fileMapper.updateByPrimaryKeySelective(file);

                //移动
                newFile.setFileId(id);
                newFile.setFileClassId(moveFile.getFileClassId());
                fileDao.updateByPrimaryKeySelective(newFile);
            }
        } else {
            //全部保留
            File file = new File();
            for (Integer id : nList) {
                File file1 = fileDao.selectByPrimaryKey(id);
                String name = file1.getOriginalFileName();
                String[] splitName = name.split("\\.");
                int i = 2;
//                while (fileMapper.selectSameFile(name, null, moveFile.getFileClassId(), userId) != null) {
//                    if (newN.length==1){
//                        name = newN[0] + "(" + i + ")";
//                    }else {
//                        name = newN[0] + "(" + i + ").";
//                    }
//                    i++;
//                }
                Integer num = fileDao.lastSameNameIndex(moveFile.getFileClassId(), splitName[0], "." + splitName[1]);
                if (num != null) {
                    i = num + 1;
                }
                name = splitName[0] + "(" + i + ")." + splitName[1];
                file.setFileId(id);
                file.setOriginalFileName(name);
                file.setFileClassId(moveFile.getFileClassId());
                fileDao.updateByPrimaryKeySelective(file);
            }
        }
        return 1;
    }

    @Override
    public UploadFileVO reName(String fileName, Integer fileId) {
        UploadFileVO uploadFileVO = new UploadFileVO();
        Integer userId = UserLoginUtils.getUser().getUserId();
        File newRecord = fileDao.selectByPrimaryKey(fileId);
        File file = fileDao.selectSameFile2(fileName, newRecord.getFileType(), newRecord.getFileClassId(), userId, fileId);
        //判断是否还重名
        if (file != null) {
            uploadFileVO.setUploadSuccess(false);
            uploadFileVO.setFileId(fileId);
            uploadFileVO.setOldFileId(file.getFileId());
            UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
            failedFile.setErrorCode(4);
            failedFile.setErrorMessage("该数据源名称已存在");
            failedFile.setFailedFileName(fileName);
            uploadFileVO.setFailedFile(failedFile);
            return uploadFileVO;
        }

        newRecord.setOriginalFileName(fileName);
        newRecord.setIsDeleted(false);
        fileDao.updateByPrimaryKeySelective(newRecord);
        uploadFileVO.setFileId(fileId);
        uploadFileVO.setUploadSuccess(true);
        UploadFileVO.FileInfo fileInfo = new UploadFileVO.FileInfo();
        fileInfo.setFileType(newRecord.getFileType());
        fileInfo.setFileSize(newRecord.getFileSize());
        fileInfo.setSavedFileName(newRecord.getSavedFileName());
        fileInfo.setOriginalFileName(fileName);
        uploadFileVO.setSuccessFile(fileInfo);
        return uploadFileVO;
    }

    private void updateFileClass(List<Integer> fileList, Integer fileClassId) {
        File updateFile = new File();
        updateFile.setFileClassId(fileClassId);
        for (Integer id : fileList) {
            updateFile.setFileId(id);
            fileDao.updateByPrimaryKeySelective(updateFile);
        }
    }

//    /**
//     * 判断是否重名，并返回重名数据
//     */
//    private List<Integer> judgeFile(List<Integer> files, List<File> fileList) {
//        List<Integer> back= new ArrayList<>();
//        //获取移动数据并与目标继续比较；
//        for (Integer id: files) {
//            //获取目标数据
//           File file = fileMapper.selectByPrimaryKey(id);
//            //循化对比
//            for (File orderFile:fileList) {
//                if (file.getFileName().equals(orderFile.getFileName())){
//                    back.add(id);
//                }
//            }
//        }
//        return back;
//    }

    private List<MoveRepeatFileVO> repeatFile(List<Integer> files, Integer fileClassId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("files", files);
        map.put("fileClassId", fileClassId);

        return fileDao.getRepeatFile(map);
    }
}
